package xyz.sicau.blog.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.sicau.blog.bean.Relation;
import xyz.sicau.blog.dao.RelationMapper;
import xyz.sicau.blog.dao.UserMapper;
import xyz.sicau.blog.utils.JwtUtils;

import javax.annotation.Resource;

@RestController
@Api(tags = "关系接口")
@RequestMapping("/relation")
public class RelationController {
    @Resource
    RelationMapper relationMapper;
    @Resource
    UserMapper userMapper;

    @RequestMapping("/relations")
    public String getRelations(String userToken) {
        int userId = JwtUtils.getUserIdByToken(userToken);
        // 这里不知道为什么只能用JSON转，不能直接回传，否则前端无法解析
        return JSON.toJSONString(relationMapper.getRelation(userId));
    }

    @RequestMapping("/new")
    public int newRelation(String userToken, String relationJson) {
        int userId = JwtUtils.getUserIdByToken(userToken);
        String userName = userMapper.getUserNameById(userId);

        Relation relation = JSON.parseObject(relationJson, Relation.class);
        relation.setCreateUserId(userId);
        relation.setCreateUserName(userName);
        System.out.println("/relation/new：" + relation);

        relationMapper.insertRelation(relation);
        return relation.getRId();
    }

    @RequestMapping("/update")
    public int updateRelation(String userToken, String relationJson) {
        int userId = JwtUtils.getUserIdByToken(userToken);
        System.out.println(userId);

        Relation relation = JSON.parseObject(relationJson, Relation.class);
        relation.setCreateUserId(userId);
        System.out.println("/relation/update：" + relation);

        return relationMapper.updateRelation(relation);
    }

    @RequestMapping("/delete")
    public int deleteRelation(String userToken, int rId) {
        int userId = JwtUtils.getUserIdByToken(userToken);
        System.out.println(userId);
        System.out.println("/relation/delete：" + rId);

        return relationMapper.deleteRelation(rId, userId);
    }


}